/**
*      author: Y_Yao
*      created: 2025-02-13 13:53:01
**/

#include<bits/stdc++.h>

#define int LL
using namespace std;
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 1e6 + 7;
int a[N];
int n;
int now;
vector<vector<int>> E(N);
vector<vector<int>> id(N);
int fa[N],s[N];
int ans = 0;

int find(int x)
{
    if(fa[x] == x) return x;
    else fa[x] = find(fa[x]);
    return fa[x];
}

void Union(int u,int v)
{
    u = find(u);
    v = find(v);
    if(u == v) return;

    ans += s[u] * s[v] * now;
    if(u > v) swap(u,v);
    fa[u] = v;
    s[v] += s[u];
}

void solve()
{
    cin >> n;
    for(int i = 1;i <= n;i++)
    {
        cin >> a[i];
        id[a[i]].push_back(i);
    }

    for(int i = 1;i <= n - 1;i++)
    {
        int u,v;
        cin >> u >> v;
        E[u].push_back(v);
        E[v].push_back(u);
    }
    for(int i = 1;i <= n;i++)
    {
        fa[i] = i;
        s[i] = 1;
    }

    for(int i = 1;i <= N;i++)
    {
        now = i;
        for(int x : id[i])
        {
            for(int v : E[x])
            {
                if(a[v] > a[x]) continue;
                Union(v,x);
            }
        }
    }

    for(int i = 1;i <= n;i++)
    {
        fa[i] = i;
        s[i] = 1;
    }

    for(int i = N;i >= 1;i--)
    {
        now = -i;
        for(int x : id[i])
        {
            for(int v : E[x])
            {
                if(a[v] < a[x]) continue;
                Union(v,x);
            }
        }
    }
    cout << ans << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    //cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}
